package com.zy.chat.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zy.chat.entity.ChatGroup;

import com.zy.chat.mapper.GroupMapper;
import com.zy.chat.service.GroupService;
import com.zy.chat.session.SingleSession;
import com.zy.chat.util.ChatRedisUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.nio.channels.Channels;
import java.util.*;


@Service
public class GroupServiceImpl extends ServiceImpl<GroupMapper, ChatGroup> implements GroupService {

    @Autowired
    private  GroupMapper groupMapper;

    @Autowired
    private ChatRedisUtils chatRedisUtils;

    String username;
    String content;
    String type;

    String groupname;

    @Override
    public ChatGroup selectByUserId(String username) {
        QueryWrapper<ChatGroup> chatGroupQueryWrapper = new QueryWrapper<>();
        chatGroupQueryWrapper.eq("user_name",username);
        return (groupMapper.selectOne(chatGroupQueryWrapper));
    }

    @Override
    public List<String> selectAllMembers(String groupname) {
        QueryWrapper<ChatGroup> wrapper = new QueryWrapper<>();
        wrapper.select("user_Name").eq("group_Name",groupname);
        List<ChatGroup> chatGroups = groupMapper.selectList(wrapper);
        ArrayList<String> members = new ArrayList<>();
        chatGroups.forEach(chatGroup ->members.add(chatGroup.getUserName()));
        return  members;
    }

    @Override
    public void GroupChat(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
        JSONObject jsonObject = JSONObject.parseObject(msg.text());
         groupname=jsonObject.getString("groupname");
        List<String> mems= selectAllMembers(groupname);
        Set<Channel> channels=new HashSet<>();
        mems.forEach(mem->channels.add(SingleSession.getUserChannelMap().get(mem).channel()));
        channels.remove(ctx.channel());
        for(Channel channel:channels ){
            channel.writeAndFlush(new TextWebSocketFrame(msg.text()));
        }
         username=jsonObject.getString("username");
        content=jsonObject.getString("content");
       type=jsonObject.getString("type");
        Map map =chatRedisUtils.createChatNumber(groupname,username,content,type);
        chatRedisUtils.hsaveCacheChatMessage(map);
    }
}
